package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradeSkuOrderBean;
import com.atguigu.func.AsyncDimFunction;
import com.atguigu.func.MyWindowFunction;
import com.atguigu.uitl.ClickHouseUtil;
import com.atguigu.uitl.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;


/**
 * @author hjy
 * @create 2023/3/18 14:11
 */

//数据流:web/app -> 业务服务器(Mysql) -> Maxwell -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> ClickHouse(DWS)
//程 序:Mock -> Mysql -> Maxwell -> Kafka(ZK) -> Dwd03_TradeOrderDetail -> Kafka(ZK) -> Dws09TradeSkuOrderWindow(Redis,Phoenix) -> ClickHouse(ZK)
public class Dws09_TradeSkuOrderWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka读取数据（dwd_trade_order_detail）
        String topic = "dwd_trade_order_detail";
        String groupId = "trade_sku_order";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //todo 3 将数据转为jsonObj对象 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSONObject.parseObject(value));
                }
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                })));
        //todo 4 按照id分组
        KeyedStream<JSONObject, String> keyedByOrderIdDS = jsonObjWithWMDS.keyBy(value -> value.getString("id"));

        //todo 5 去重并转为javaBean对象
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanDS = keyedByOrderIdDS.flatMap(new RichFlatMapFunction<JSONObject, TradeSkuOrderBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("value-state", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeSkuOrderBean> out) throws Exception {
                String lastValue = valueState.value();
                if (lastValue == null) {
                    valueState.update("1");
                    BigDecimal split_activity_amount = value.getBigDecimal("split_activity_amount");
                    BigDecimal split_coupon_amount = value.getBigDecimal("split_coupon_amount");
                    if (split_activity_amount == null) {
                        split_activity_amount = new BigDecimal("0.0");
                    }
                    if (split_coupon_amount == null) {
                        split_coupon_amount = new BigDecimal("0.0");
                    }
                    out.collect(TradeSkuOrderBean.builder()
                            .skuName(value.getString("sku_name"))
                            .skuId(value.getString("sku_id"))
                            .originalAmount(value.getBigDecimal("split_original_amount"))
                            .orderAmount(value.getBigDecimal("split_total_amount"))
                            .activityAmount(split_activity_amount)
                            .couponAmount(split_coupon_amount)
                            .build());
                }
            }
        });

        //todo 6 分组开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> reduceDS = tradeSkuOrderBeanDS.keyBy(TradeSkuOrderBean::getSkuId)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        return value1;
                    }
                }, new WindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TradeSkuOrderBean> input, Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getJavaBeanField(next, window));
                    }
                });
        reduceDS.print("reduceDS>>>>>>>>>>>>>>>>>");
        //todo 7 关联8表
        //从phoenix读取数据，进行关联   优化后先查询redis 没有在从phoenix读取
        //todo 在实现异步io之前，
        // 需要先定义一个线程池的工具类,然后自定义异步IO的实现类，继承 RichAsyncFunction<String, Tuple2<String, String>> 面向官网编程
        //关联sku_info
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithSku = AsyncDataStream.unorderedWait(reduceDS, new AsyncDimFunction<TradeSkuOrderBean>("DIM_SKU_INFO") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String tmId = dimInfo.getString("TM_ID");
                String category3Id = dimInfo.getString("CATEGORY3_ID");
                String spuId = dimInfo.getString("SPU_ID");
                input.setTrademarkId(tmId);
                input.setCategory3Id(category3Id);
                input.setSpuId(spuId);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getSkuId();
            }
        }, 60, TimeUnit.SECONDS);

        //关联spu_info
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithSpu = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithSku, new AsyncDimFunction<TradeSkuOrderBean>("DIM_SPU_INFO") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String supName = dimInfo.getString("SPU_NAME");
                System.out.println(supName+"supName>>>>>>>>>>>>>>>>>");
                input.setSpuName(supName);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getSpuId();
            }
        }, 60, TimeUnit.SECONDS);
        //关联base_tardemark
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithTrademark = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithSpu, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_TRADEMARK") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String tmName = dimInfo.getString("TM_NAME");
                input.setTrademarkName(tmName);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getTrademarkId();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory3 = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithTrademark, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY3") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String name = dimInfo.getString("NAME");
                String category2Id = dimInfo.getString("CATEGORY2_ID");
                input.setCategory3Name(name);
                input.setCategory2Id(category2Id);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getCategory3Id();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory2 = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithCategory3, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY2") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String name = dimInfo.getString("NAME");
                String category1Id = dimInfo.getString("CATEGORY1_ID");
                input.setCategory2Name(name);
                input.setCategory1Id(category1Id);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getCategory2Id();
            }
        }, 60, TimeUnit.SECONDS);


        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanWithCategory1 = AsyncDataStream.unorderedWait(tradeSkuOrderBeanWithCategory2, new AsyncDimFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY1") {
            @Override
            public void joinInfo(TradeSkuOrderBean input, JSONObject dimInfo) {
                String name = dimInfo.getString("NAME");
                input.setCategory1Name(name);
            }

            @Override
            public String getId(TradeSkuOrderBean input) {
                return input.getCategory1Id();
            }
        }, 60, TimeUnit.SECONDS);

        //TODO 9.将数据写出
        tradeSkuOrderBeanWithCategory1.print("tradeSkuOrderWithCategory1DS>>>>>>>>");
        tradeSkuOrderBeanWithCategory1.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_sku_order_window values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        //TODO 10.启动
        env.execute("Dws09TradeSkuOrderWindow");

    }
}
